package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 *自定义定时任务
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    //订单超时任务
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeOutTask(){
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);//执行的时间点
        //分析执行时间，执行规则：多久执行，查询是否存在待支付订单
        List<Orders> list=orderMapper.getByOutTimeAndStatus(time,Orders.PENDING_PAYMENT);
        if (list!=null && list.size()!=0){
            for (Orders order : list) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时，自动取消");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            }
        }
    }

    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        //每天定时处理一直处于派送中的订单
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-60);//这样就是处理前一天的订单
        List<Orders> orders = orderMapper.getByOutTimeAndStatus(localDateTime, Orders.DELIVERY_IN_PROGRESS);
        if (orders!=null && orders.size()!=0){
            for (Orders order : orders) {
                order.setStatus(Orders.COMPLETED);//自动完成
                orderMapper.update(order);
            }
        }
    }


}
